package com.yuke.cloud.service.opc.controller.frontend;

import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.opc.service.OpcFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Api(value="WEB - FileUploadController",tags="处理图片文件上传相关请求",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
@RestController
public class FileUploadController extends BaseController {
    @Resource
    private OpcFileService opcFileService;

    @PostMapping("/base64images/upload/{amount}")
    @ApiOperation(httpMethod = "POST", value = "上传图片")
    public Wrapper<List<String>> fileUpload(HttpServletRequest request,
                                                @ApiParam(name = "jsonObject", value = "上传的图片")   @RequestBody JSONObject jsonObject,
                                                @ApiParam(name = "amount", value = "需要上传图片的数量") @PathVariable int amount) {
        log.info("----- Enter '/base64images/upload/{}' fileUploadMall() -----", amount);

        List<String> pathList = this.fileUploadMall(request,jsonObject, amount).getResult();
        log.info("----- Leave '/base64images/upload/{}' fileUploadMall() -----", amount);
        return WrapMapper.ok(pathList);
    }

    @PostMapping("/mall/baseimages/upload/{amount}")
    @ApiOperation(httpMethod = "POST", value = "上传图片")
    public Wrapper<List<String>> fileUploadMall(HttpServletRequest request,
                                                @ApiParam(name = "content", value = "需要上传图片的数量") @RequestBody JSONObject jsonObject,
                                                @ApiParam(name = "amount", value = "需要上传图片的数量")@PathVariable int amount) {
        String content = jsonObject.getString("content");
        log.info("----- Enter '/mall/baseimages/upload/{}' fileUploadMall() -----", amount);
        List<String> pathList = new ArrayList<>();
        if (content == null) {
            log.info("The incoming file is null");
            return WrapMapper.error("传入文件为空，请重新上传");
        }
        String sysFilePath = request.getSession().getServletContext().getRealPath("/");
        System.out.println("sysFilePath="+sysFilePath);

        String newFileName = String.valueOf(generateId());
        GenerateImage(content, sysFilePath + "/" + newFileName + ".jpg");
        File file = new File(sysFilePath + "/" + newFileName + ".jpg");

        String fileName = file.getName();
        String ext =  fileName.substring(fileName.lastIndexOf(".") + 1);
        InputStream smallInputStream = null;
        try {
            if (amount == 1) {
                InputStream inputStream = new FileInputStream(file);
                pathList.add(opcFileService.saveFiles(inputStream, fileName, ext));
            }
            if (amount == 2) {
                smallInputStream = disposeImage(file, 100, 100);
                pathList.add(opcFileService.saveFiles(smallInputStream, fileName, ext));
            }
        } catch (Exception e) {
            log.error("Upload file failed",e);
        }
        log.info("----- Leave '/image/upload/{}' fileUpload() -----", amount);
        return WrapMapper.ok(pathList);

    }

    private synchronized static InputStream disposeImage(File file, int new_w, int new_h) {
        log.info("----- Enter disposeImage() -----");
        InputStream inputStream = null;
        String fileName = file.getName();
        BufferedImage srcBufferedImage = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            srcBufferedImage = ImageIO.read(file);
            BufferedImage newBufferedImage = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = newBufferedImage.createGraphics();
            graphics.drawImage(srcBufferedImage, 0, 0, srcBufferedImage.getWidth(), srcBufferedImage.getHeight(), null);
            graphics.dispose();
            newBufferedImage.getGraphics().drawImage(srcBufferedImage.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
            ImageIO.write(newBufferedImage, fileName.substring(fileName.lastIndexOf(".") + 1), byteArrayOutputStream);
            inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        } catch (IOException e) {
            log.error("IO Exception : ", e);
        } finally {
            try {
                inputStream.close();
                byteArrayOutputStream.close();
            } catch (IOException e) {
                log.error("IO Exception : Stream close() fail", e);
            }
        }
        log.info("----- Leave disposeImage() -----");
        return inputStream;
    }

    /**
     *  base64 转成图片
     * @param imgStr
     * @param imgFilePath
     * @return
     */
     public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        // 图像数据为空
        if (imgStr == null) {
            return false;
        }

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}